#include "signing.h"
#include "common.h"
#include "conversion.h"
#include "kerl.h"

//extern Conversion* pConversion;


Signing::Signing(Keccak384* keccak, const uint8_t* seedBytes, uint32_t addressIndex) {
	m_keccak = keccak;
	m_addressIndex = addressIndex;

	memcpy(m_state, seedBytes, 48);

	Conversion conv;
	conv.bytes_add_u32_mem(m_state, m_addressIndex);

	Kerl::initialize(m_keccak);
	Kerl::absorbChunk(m_keccak, m_state);
	Kerl::squeezeFinalChunk(m_keccak, m_state);
}

bool Signing::sign(Transaction* tx, tryte_t* bundleHashFragment) {
	Kerl::reinitialize(m_keccak, m_state);

    char* pSignatureMessageFragment = tx->getsignatureMessageFragment();
    for (unsigned int j = 0; j < 27; j++) {
        uint8_t signatureBytes[48]={0};

        Kerl::reinitialize(m_keccak, m_state);
        // the output of the squeeze is exactly the private key
        Kerl::stateSqueezeChunk(m_keccak, m_state, signatureBytes);

        for (unsigned int k = MAX_TRYTE_VALUE - bundleHashFragment[j]; k-- > 0;) {
        	Kerl::initialize(m_keccak);
        	Kerl::absorbChunk(m_keccak, signatureBytes);
        	Kerl::squeezeFinalChunk(m_keccak, signatureBytes);
        }
        Conversion conv;
        conv.bytes_to_chars(signatureBytes, pSignatureMessageFragment, 48);
    	pSignatureMessageFragment += 81;
    }
    return true;
}

